package com.b2s.scrumblr.kb.controller;

import com.b2s.scrumblr.kb.model.Article;
import com.b2s.scrumblr.kb.model.User;
import com.b2s.scrumblr.kb.service.ArticleSolrService;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * Created by Administrator on 2016/8/11.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private ArticleSolrService articleSolrService;


    @RequestMapping("/search")
    public String search(String searchParam, Model model, HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {

        User user = (User)request.getSession().getAttribute("user");
        System.out.println(user.getId());
        model.addAttribute("page", articleSolrService.findHighlight(searchParam));
        return "result";
    }

    @RequestMapping("/save")
    @ResponseBody
    public String save(Article article, HttpServletRequest request){
        System.out.println(request.getServletPath());
        String contextPath = request.getServletContext().getContextPath();
        String articlePath = request.getServletContext().getRealPath("/article");
        File file = new File(articlePath + "/" + System.currentTimeMillis() + ".html");
        articleSolrService.save(article, file);
        return "success";
    }

    @RequestMapping("/my_articles")
    public String getMyArticles(HttpSession session, Model model){
        List<Article> articles = articleSolrService.getMyArticles((String)session.getAttribute("username"));
        model.addAttribute("articles", articles);
        return "my_articles";
    }

    @RequestMapping("delete")
    @ResponseBody
    public String delete(String id){
        articleSolrService.deleteById(id);
        return "success";
    }
}
